import {
	ref
} from 'vue'
export function userList(config = {}) {
	const status = ref('loadmore')
	const tableData = ref([])
	const queryForm = ref({
		pageNo: 1,
		pageSize: config?.size || 10
	})
	if (config?.initForm) {
		queryForm.value = {
			...queryForm.value,
			...JSON.parse(JSON.stringify(config.initForm)),
		}
	}
	let isRefresh = false

	/**
	 * 数据列表
	 * */

	const fetchData = (param = {}) => {
		status.value = 'loading'
		const params = {
			...queryForm.value,
			...param,
		}
		return config.apis.getApi(params).then((data) => {
			if (params.pageNo === 1) {
				tableData.value = data.records
			} else {
				tableData.value = [...tableData.value, ...data.records]
			}
			status.value = params.pageSize === data.records.length ? 'loadmore' : 'nomore'
			queryForm.value.pageNo++
			if (isRefresh) {
				uni.stopPullDownRefresh();
			}
		}).catch(err => {
			uni.stopPullDownRefresh();
		})
	}

	const handDel = (index) => {
		tableData.value.splice(index, 1)
	}

	const onBottom = () => {
		if (status.value == 'nomore') return
		fetchData()
	}

	const onRefresh = () => {
		isRefresh = true
		status.value = 'loading'
		tableData.value = []
		queryForm.value.pageNo = 1
		fetchData()
	}

	return {
		fetchData,
		status,
		tableData,
		onBottom,
		onRefresh,
		handDel,
		queryForm
	}
}